package ssm.dao.impl;


import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanHandler;
import ssm.dao.UserDao;
import ssm.pojo.User;
import util.Dbutil;


import java.sql.SQLException;

public class UserDaoImpl implements UserDao {
    @Override
    public User foundUName(String name) throws SQLException {
        QueryRunner qr = new QueryRunner(Dbutil.getDataSource());
        String sql = "select * from user where username=?";
        User query = qr.query(sql, new BeanHandler<User>(User.class), name);

        return query;
    }

    public int addUser(User user) throws SQLException {
        QueryRunner qr = new QueryRunner(Dbutil.getDataSource());
        String sql = "insert into user values(?,?,?,?,?,?,?,?,?,?)";
        int update = qr.update(sql,
                user.getUid(),
                user.getUsername(),
                user.getPassword(),
                user.getName(),
                user.getEmail(),
                user.getTelephone(),
                user.getBirthday(),
                user.getSex(),
                user.getState(),
                user.getCode()
        );
        return update;

    }

    @Override
    public User founduByCode(String code) throws SQLException {
        QueryRunner qr = new QueryRunner(Dbutil.getDataSource());
        String sql = " select * from user where code=?";
        User query = qr.query(sql, new BeanHandler<User>(User.class), code);
        return query;
    }

    public void updateUser(User user) throws SQLException {
        QueryRunner qr = new QueryRunner(Dbutil.getDataSource());
        String sql = "update user set state=? where uid=? ";
        int update = qr.update(sql, user.getState(), user.getUid());
    }

    @Override
    public User loginUser(String username) throws SQLException {
        QueryRunner qr = new QueryRunner(Dbutil.getDataSource());
        String sql = "select * from user where username = ?";
        User user = qr.query(sql, new BeanHandler<User>(User.class), username);

        return user;
    }

}
